package com.redis.springtest;

import com.redis.springtest.config.RedisConfig;
import io.lettuce.core.api.async.RedisAsyncCommands;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-04-21 下午5:22
 */
@Slf4j
public class AppRedisHash {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
        final RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);

        final String key = "hash";
        Map<String, String> map = new HashMap<>(16);
        map.put("key1", "value1");
        map.put("key2", "value2");

        final HashOperations hashOperations = redisTemplate.opsForHash();
        final RedisAsyncCommands<Object, Object> nativeConnection = (RedisAsyncCommands<Object, Object>) redisTemplate.getConnectionFactory()
                .getConnection()
                .getNativeConnection();
        log.info(nativeConnection.getClass().getName());

        // 相当于hmset命令
        hashOperations.putAll(key, map);
        // 相当于hset命令
        hashOperations.put(key, "f3", "6");
        print(hashOperations, "f3");

        // 相当于hexists key field命令
        final Boolean hasKey = hashOperations.hasKey(key, "f3");
        log.info("f3 exit?{}", hasKey);

        // 相当于hgetall命令
        final Map entries = hashOperations.entries(key);

        // 相当于hincrby命令
        final Long f3 = hashOperations.increment(key, "f3", 2);
        print(hashOperations, "f3");

        // 相当于hincrbyfloat
        final Double f31 = hashOperations.increment(key, "f3", 0.88);
        print(hashOperations, "f3");

        // 相当于hvals命令
        final List values = hashOperations.values(key);

        // 相当于hkeys命令
        final Set keys = hashOperations.keys(key);
        List<String> fieldList = new ArrayList<>();
        fieldList.add("f1");
        fieldList.add("f2");
        // 相当于hmget命令
        final List multiGet = hashOperations.multiGet(key, fieldList);
        // 相当于hetnx命令
        final Boolean putIfAbsent = hashOperations.putIfAbsent(key, "f4", "val4");
        log.info("set success?{}", putIfAbsent);
        // 相当于hdel命令
        final Long delete = hashOperations.delete(key, "f1", "f2");
        log.info("delete {} fields from {}", delete, key);
    }

    private static void print(HashOperations hashOperations, String field) {
        final String key = "hash";
        // 相当于hget命令
        final Object value = hashOperations.get(key, field);
        log.info("field {}:{}", field, value);
    }
}
